package ru.spb.osll.myfit.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import ru.spb.osll.myfit.client.dialog.ErrorDialog;
import ru.spb.osll.myfit.client.event.PageButtonEvent;
import ru.spb.osll.myfit.client.service.PageExecutingService;
import ru.spb.osll.myfit.client.service.PageExecutingServiceAsync;
import ru.spb.osll.myfit.client.widget.PageButtonEventListener;
import ru.spb.osll.myfit.common.PageExecutingResult;


/**
 * User: Artem Bukhonov
 * Email: nerzhulart@gmail.com
 * Date: 10.12.11
 * Time: 18:12
 */
public class TestResultViewController implements IViewController {

  private final PageExecutingServiceAsync m_pageExecutingService =
                                    GWT.create(PageExecutingService.class);
  private final ErrorDialog errorDialog = new ErrorDialog();
  private TestResultView m_TestResultView;
  private String m_id;

  @Override
  public IView getView(String address) {
    m_TestResultView = new TestResultView(createButtonEventListener());
    m_id = Window.Location.getParameter("id");
    m_pageExecutingService.getExecutingResult(m_id, new AsyncCallback<PageExecutingResult>() {
      @Override
      public void onFailure(Throwable caught) {
        errorDialog.setMessage(caught);
        errorDialog.center();
      }

      @Override
      public void onSuccess(PageExecutingResult pageExecutingResult) {
        if(pageExecutingResult != null){
          m_TestResultView.displayResult(pageExecutingResult);
        }else{
          errorDialog.setMessage("Test with id = " + m_id + " not found");
          errorDialog.center();
        }
      }
    });
    return m_TestResultView;
  }

  private PageButtonEventListener createButtonEventListener() {
    PageButtonEventListener listener = new PageButtonEventListener() {
      @Override
      public void actionPerformed(PageButtonEvent event) {
        switch (event.getType()) {
          case SAVE_METADATA:
            saveMetadata();
            break;
          default:
            break;
        }
      }
    };
    return listener;
  }

  private void saveMetadata() {
    m_pageExecutingService.saveMetadata(m_TestResultView.getMetadata(), m_id, new AsyncCallback<Void>() {
      @Override
      public void onFailure(Throwable caught) {

      }

      @Override
      public void onSuccess(Void result) {

      }
    });
  }
}
